package ro.imv.server.gcmDatastore;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ro.imv.server.gcmDatastore.utils.EntityUtils;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;

@SuppressWarnings("serial")
public class RegisterGCMClient extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String registrationId = req.getParameter("registrationId");
		String senderId = req.getParameter("senderId");
		Key addedKey = null;
		Boolean ok = false;
		if(null != registrationId && null != senderId){
			try{
				DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
				if(!EntityUtils.entityExists(datastore ,senderId, registrationId)){
					Entity entity = new Entity("Client");
					entity.setProperty("registrationId", registrationId);
					entity.setProperty("senderId", senderId);
					
					datastore.put(entity);
					addedKey = entity.getKey();
					resp.setContentType("text/plain");
					resp.getWriter().println("OK!");
					resp.getWriter().println("Added key: " + addedKey.getId());
					resp.getWriter().println("Registered this registrationId: " + registrationId);
					resp.getWriter().println("senderId: " + senderId);
					ok = true;
				}
				
			}catch(Exception e){
				e.printStackTrace();
				resp.setContentType("text/plain");
				resp.getWriter().println("NK!");
			}
		}else{
			resp.setContentType("text/plain");
			resp.getWriter().println("Parameters not set(registrationId,senderId)");
		}
		
		
	}
}
